package com.taxi.management.config;

import com.taxi.management.service.Impl.TokenServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
//urlPatterns:需要对哪些url进行过滤，例如：/user/* 就会对 /user/下面的所有URL进行过滤。*：通配所有
//filterName：过滤器名称

@WebFilter(urlPatterns = "/*", filterName = "WebXFilter")
public class WebXFilter extends HttpFilter {
    @Resource
    TokenServiceImpl tokenService;

    public void init(FilterConfig config) throws ServletException {
        System.out.println("创建过滤器");
    }

    public void destroy() {
        System.out.println("销毁过滤器");
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream servletOutputStream = response.getOutputStream();//输出对象
        try {
            if (request.getMethod().equals("OPTIONS")) { //预检，统统通过
                chain.doFilter(request, response);//继续向下（通过当前过滤器）
            } else {
                if (!request.getRequestURI().equals("/v3/user/doLogin")) {
                    String token = request.getHeader("token");
                    if (token == null) {
                        servletOutputStream.write("{\"code\":0,\"msg\":\"Token错误或者不存在！\"}".getBytes());
                    }
                    chain.doFilter(request, response); // 放行所有请求，交由 Interceptor 处理权限
                } else {//登录接口（直接通过）
                    chain.doFilter(request, response);//继续向下（通过当前过滤器）
                }
            }

        } catch (Exception e) {
            servletOutputStream.write("{\"code\":-1,\"msg\":\"未传入Token！\"}".getBytes());
        }
    }
}
